<!-- 商品详情 -->
<template>
	<view class="GoodDetails">
		<view class="search-top box-sizing dis-ali pof width100"
			:style="{ paddingTop: `${getSystemInfo.statusBarTop}rpx`, height: `${getSystemInfo.statusBarHeight}rpx` }"
			:class="{'search-opacity':scrollTop>0}">
			<view class="index dis" @click="previousPage" v-if="!beforePage">
				<text class="iconfont icon-shouye1 color0 size-48 font-weight-600"></text>
			</view>
			<view class="return dis" @click="previousPage" v-else>
				<text class="iconfont icon-zuo color0 size-36 font-weight-600"></text>
			</view>
		</view>
		<!-- <canvas canvas-id="myCanvas" style="width: 500rpx; height: 400rpx;"></canvas> -->
		<swiper class="swiper">
			<swiper-item v-for="(item,index) in swiperList" :key="index">
				<image class="width-height100" :src="item" mode="" @click="onPreviewImage(index)"></image>
			</swiper-item>
		</swiper>
		<view class="details margin-bottom-16 f-background por">
			<view class="details-share">
				<view class="font-weight-600 color3 size-46">{{goodsInfo.goodsName || '-'}}</view>
				<view class="share text-align por">
					<text class="iconfont icon-fenxiang_2 color3 size-48 font-weight-600"></text>
					<view class="size-20 color5">分享</view>
					<button open-type="share" class="share-button poa app-top app-left width-height100"></button>
				</view>
			</view>
			<view class="color-8 size-26">买贵了包退，赠便利豆</view>
			<view class="details-par size-50 color0 font-weight-600">¥{{goodsInfo.goodsAmount || 0}}</view>
			<view class="dis-cen size-26">
				<text class="color">超低价</text>
				<text class="color3">已售{{goodsInfo.goodsSales || 0}}</text>
			</view>
		</view>
		<view class="service dis-ali size-26 margin-bottom-16 f-background">
			<view class="font-weight-600 color3">服务</view>
			<view class="color-8 margin-left-24">小时达丨免配送</view>
		</view>
<!-- 		<view class="service dis-ali size-26 margin-bottom-16 f-background">
			<view class="font-weight-600 color3">承诺</view>
			<view class="color-8 margin-left-24">买贵了包退丨先送后付丨免配送费丨赠便利豆</view>
		</view> -->
		<view class="carts-pof pof width100 f5-background">
			<view class="dis-cen">
				<view class="carts dis por" @click="onJumpPage">
					<view class="carts-num background dis poa" v-if="goodsInfo.goodsCount*1">
						<text class="font-weight-600 color-f size-22">
							{{goodsInfo.goodsCount*1 > 99 ? '99+' : goodsInfo.goodsCount}}
						</text>
					</view>
					<text class="iconfont icon-shiwu-gouwuche color2" :class="{'swings':swingsBool}"></text>
				</view>
				<u-button type="primary"
					:customStyle="{width: '510rpx',height: '104rpx',borderRadius: '100rpx',margin: 0,boxShadow: '0rpx 8rpx 16rpx 4rpx rgba(0,0,0,0.1)'}"
					color="#EB0000" @click="onAddCart">
					<text class="color-f size-34 font-weight-600">加入购物车</text>
				</u-button>
			</view>
		</view>
	</view>
</template>

<script>
	import { onPriceCut, getSystemInfo } from '@/utils/index';
	import { GetGoodsInfoByIds, AddUpdGoodsCart } from '@/api/index'
	import { appId } from "@/utils/public"
	export default {
		data() {
			return {
				getSystemInfo: getSystemInfo(), // 顶部自定义导航数据
				scrollTop: 0,
				cartShopList: [],
				beforePage: "",
				id: 0,
				swingsBool: false,
				goodsInfo: {},
				swiperList: []
			}
		},
		onLoad(options) {
			const pages = getCurrentPages(); //当前页
			let beforePage = (pages[pages.length - 2]); //上个页面、
			this.beforePage = beforePage
			console.log('beforePage', beforePage)
			this.id = options.id
			this.postGetGoodsInfoByIds()
		},
		onShow() {
			this.canReset && this.postGetGoodsInfoByIds()
			this.canReset = true // 过滤第一次的onShow事件
		},
		onPageScroll(res) {
			this.scrollTop = res.scrollTop;
		},
		onShareAppMessage(res) {
			let { goodsInfo, swiperList } = this
			return {
				title: `${goodsInfo.goodsName || ''} ￥${goodsInfo.goodsAmount || '0.00'}`, //
				path: `/packageReplace/current-lives/good-details?id=${goodsInfo.id}`, //
				imageUrl: swiperList[0],
				mpId: appId, //此处配置微信小程序的AppId
			};
		},
		methods: {
			onPriceCut,
			// 查看详情
			async postGetGoodsInfoByIds(bool) {
				const { code, data } = await GetGoodsInfoByIds({ goodsId: this.id })
				if (code == '200') {
					this.goodsInfo = data
					this.swiperList = data.goodsUrl.split(',')
					// this.drawCircleWithText()
					if (bool) uni.$u.toast('操作成功', 1000)
				}
			},
			drawCircleWithText() {
				const ctx = uni.createCanvasContext('myCanvas', this);
				// 假设这是你的OSS图片URL  
				const imageUrl = this.swiperList[0]

				// 创建一个新的Image对象  
				const img = new Image();

				// 设置图片加载完成后的回调函数  
				img.onload = () => {
					// 绘制图片到canvas，这里设置图片的宽高为250x200  
					ctx.drawImage(img, 0, 0, 250, 200);
					// 绘制完成后，将画布内容输出显示  
					ctx.draw(true, () => {
						console.log('图片绘制完成');
					});
				};

				// 设置图片源，开始加载图片  
				img.src = imageUrl;
				// ctx.fill();
				// 绘制红色圆形  
				ctx.setFillStyle('red');
				ctx.arc(215, 165, 25, 0, 2 * Math.PI);
				ctx.fill();

				// 设置字体大小和字体类型  
				ctx.setFontSize(13);

				// 测量文字宽度  
				const texts = ['免 配', '送 费'];
				let totalWidth = 0;
				let maxHeight = 0;
				texts.forEach(text => {
					const width = ctx.measureText(text).width;
					totalWidth = Math.max(totalWidth, width); // 取最宽行的宽度作为参考  
					// 这里假设每行高度相同，实际可能需要根据字体等属性计算  
					const fakeHeight = 16; // 假设行高为字体大小  
					maxHeight = Math.max(maxHeight, fakeHeight);
				});

				// 计算文字绘制的位置  
				// 圆心坐标(50, 50)，半径50，因此文字的绘制范围大致在(25, 25)到(75, 75)之间  
				// 假设我们要将文字绘制在圆形的中心偏下一点（因为有两行）  
				const startX = 215 - totalWidth / 2; // 水平居中  
				const startY = 156 + (maxHeight / 2) * 0.5; // 垂直居中的起始点（第一行）  

				// 绘制文字  
				ctx.setFillStyle('white');
				texts.forEach((text, index) => {
					const y = startY + index * (maxHeight * 1.2); // 假设行间距为字体大小的1.2倍  
					ctx.fillText(text, startX, y);
				});

				// 绘制操作提交  
				ctx.draw(true);
			},
			drawCanvas() {
				const ctx = uni.createCanvasContext('myCanvas', this);
				console.log('this.swiperList[0]', this.swiperList[0])
				ctx.drawImage(this.swiperList[0], 0, 0, 250, 200); // 绘制背景图，与 Canvas 大小一致  

				// // 绘制红色圆形  
				// ctx.setFillStyle('red');
				// ctx.beginPath();
				// ctx.arc(50, 175, 50, 0, 2 * Math.PI); // 圆心在(50, 175)，半径为50  
				// ctx.fill();

				// // 设置字体大小和字体类型  
				// ctx.setFontSize(16);
				// // 绘制“免费配送”文字  
				// const texts = ['免费', '配送'];
				// let maxWidth = 0;
				// texts.forEach(text => {
				// 	maxWidth = Math.max(maxWidth, ctx.measureText(text).width);
				// });

				// // 计算文字绘制的起始位置  
				// const startX = 50 + (50 - maxWidth) / 2; // 圆形中心 X 减去文字宽度的一半  
				// const startY = 175 - 16; // 圆形中心 Y 减去字体大小的一半（这里假设行高与字体大小相同）  

				// // 绘制每行文字  
				// texts.forEach((text, index) => {
				// 	const y = startY + index * 18; // 假设行间距为字体大小的1.125倍（16px * 1.125 = 18px）  
				// 	ctx.fillText(text, startX, y);
				// });

				// 绘制操作提交  
				ctx.draw(true);
			},
			// 添加购物车数据
			onAddCart() {
				// console.log('list', )
				const { goodsInfo } = this
				let nums = 0
				const _this = this
				if (this.swingsBool) return
				if (goodsInfo.goodsCount * 1 + 1 > goodsInfo.stock * 1) {
					uni.$u.toast('已经达到最大库存', 1000)
					return
				}
				_this.swingsBool = true
				setTimeout(() => {
					_this.swingsBool = false
				}, 500)
				this.postAddUpdGoodsCart(this.id, goodsInfo.goodsCount * 1 + 1)
			},
			// 修改购物车数据
			async postAddUpdGoodsCart(id, num, name) {
				const carts = {
					isDel: !num ? 1 : 0,
					goodsId: id,
					goodsCount: num,
					communityId: this.goodsInfo.communityId
				}
				const { data, code } = await AddUpdGoodsCart(carts)
				if (code == '200') {
					this.postGetGoodsInfoByIds(true)
				}
			},
			// 返回上一页 或者首页
			previousPage() {
				if (this.beforePage && this.beforePage.route) { // 有的时候 返回上一页
					uni.navigateBack({});
				} else { // 没有上一页返回首页
					uni.switchTab({
						url: '/pages/pages/index'
					});
				}
			},
			// 查看大图
			onPreviewImage(index) {
				console.log(index)
				uni.previewImage({
					current: index,
					urls: this.swiperList
				});
			},
			onJumpPage() {
				uni.navigateTo({
					url: '/packageReplace/shopping-cart/shopping-cart'
				});
			}
		}
	}
</script>

<style lang="scss">
	.GoodDetails {
		padding-bottom: 222rpx;

		.search-top {
			z-index: 10000;
			padding-left: 30rpx;
			box-sizing: border-box;

			.return {
				width: 60rpx;
				height: 60rpx;
				background: #FFFFFF;
				border-radius: 60rpx 60rpx 60rpx 60rpx;
				border: 2rpx solid rgba(153, 153, 153, 0.3);
				box-sizing: border-box;

				.icon-zuo {
					margin-left: -5rpx;
				}
			}

			.index {
				width: 88rpx;
				height: 60rpx;
				background: #FFFFFF;
				border-radius: 30rpx;
				border: 2rpx solid rgba(153, 153, 153, 0.3);
			}
		}

		.swiper {
			height: 750rpx;
		}

		.service {
			padding: 36rpx 30rpx;
		}

		.details-share {
			display: flex;
			justify-content: space-between;

			.share {}

			.size-46 {
				line-height: 60rpx;
			}
		}

		.details {
			padding: 80rpx 40rpx 36rpx 32rpx;
			border-radius: 26rpx 26rpx 0rpx 0rpx;
			margin-top: -30rpx;
			position: relative;
			z-index: 10;

			.details-par {
				margin: 70rpx 0 28rpx;
			}
		}

		.share-button {
			background: rgba(0, 0, 0, 0);
		}

		.share-button::after {
			border: 0;
		}

		.carts {
			width: 104rpx;
			height: 104rpx;
			background: #FFFFFF;
			box-shadow: 0rpx 6rpx 12rpx 4rpx rgba(0, 0, 0, 0.06);
			border-radius: 60rpx;

			.icon-shiwu-gouwuche {
				font-size: 54rpx;
			}

			.swings {
				animation: swing .5s;
			}

			.carts-num {
				min-width: 30rpx;
				height: 30rpx;
				padding: 0 5rpx;
				box-sizing: border-box;
				border-radius: 30rpx;
				right: 16rpx;
				top: 16rpx;
				z-index: 100;
			}
		}

		.carts-pof {
			padding: 32rpx 32rpx 70rpx;
			box-sizing: border-box;
			bottom: 0;
		}
	}
</style>